<template>
  <div>
    <van-nav-bar
      title="收货地址"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <div class="address-card" v-for="(address, index) in addresses" :key="index">
      <div class="address-header">
        <span class="name">{{ address.name }}</span>
        <span class="phone">{{ address.phone }}</span>
      </div>
      <div class="address-body">
        {{ address.region }} {{ address.detailAddress }}
      </div>
      <hr class="divider"/>
      <div class="address-footer">
        <label>
          <input type="radio" v-model="selectedAddress" :value="index" @change="setDefaultAddress(index)" />
          设为默认
        </label>
        <div class="buttons">
          <van-button type="primary" size="mini" plain @click="onEdit(index)">修改</van-button>
          <van-button type="danger" size="mini" plain @click="onDelete(index)">删除</van-button>
        </div>
      </div>
    </div>

    <van-button class="bottom-button" type="primary" block @click="showForm">
      添加地址
    </van-button>

    <!-- Dialog for Add/Edit Address -->
    <van-dialog v-model:show="showDialog" title="添加地址" @confirm="onSave">
      <van-form>
        <van-field v-model="formData.name" label="收货人" placeholder="请输入收货人" />
        <van-field v-model="formData.phone" label="手机号" placeholder="请输入手机号" type="tel"/>
        <van-field v-model="formData.region" label="地区" placeholder="请输入地区"/>
        <van-field v-model="formData.detailAddress" label="详细地址" placeholder="请输入详细地址"/>
      </van-form>
    </van-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue';
import { Button, Dialog, Field, Form, NavBar } from 'vant';

const onClickLeft = () => {
  history.back();
};

const loadAddresses = () => {
  const storedAddresses = localStorage.getItem('addresses');
  return storedAddresses ? JSON.parse(storedAddresses) : [
    { name: '张三', phone: '13800138000', region: '四川省 成都市 武侯区', detailAddress: '武侯大道' },
    { name: '李四', phone: '13800138001', region: '北京市 海淀区', detailAddress: '中关村' }
  ];
};

const addresses = ref(loadAddresses());

const selectedAddress = ref(0);

const showDialog = ref(false);
const formData = ref({ name: '', phone: '', region: '', detailAddress: '' });
const editIndex = ref(-1);

const showForm = () => {
  formData.value = { name: '', phone: '', region: '', detailAddress: '' };
  editIndex.value = -1;
  showDialog.value = true;
};

const onEdit = (index: number) => {
  formData.value = { ...addresses.value[index] };
  editIndex.value = index;
  showDialog.value = true;
};

const onSave = () => {
  if (editIndex.value === -1) {
    // Add new address
    addresses.value.push({ ...formData.value });
  } else {
    // Update existing address
    addresses.value.splice(editIndex.value, 1, { ...formData.value });
  }
  showDialog.value = false;
};

const onDelete = (index: number) => {
  addresses.value.splice(index, 1);
  if (selectedAddress.value === index) {
    selectedAddress.value = addresses.value.length > 0 ? 0 : -1;
  }
};

const setDefaultAddress = (index: number) => {
  const defaultAddress = addresses.value.splice(index, 1)[0];
  addresses.value.unshift(defaultAddress);
  selectedAddress.value = 0;
};

// Watch for changes in addresses and save to localStorage
watch(addresses, (newAddresses) => {
  localStorage.setItem('addresses', JSON.stringify(newAddresses));
}, { deep: true });

onMounted(() => {
  const storedSelectedAddress = localStorage.getItem('selectedAddress');
  if (storedSelectedAddress !== null) {
    selectedAddress.value = parseInt(storedSelectedAddress, 10);
  }
});

// Watch for changes in selectedAddress and save to localStorage
watch(selectedAddress, (newSelectedAddress) => {
  localStorage.setItem('selectedAddress', newSelectedAddress.toString());
});
</script>

<style scoped>
.address-card {
  border: 1px solid #ebedf0;
  padding: 16px;
  border-radius: 8px;
  margin: 16px;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  margin-right: 30px;
}

.phone {
  font-weight: bold;
}

.address-body {
  margin-bottom: 16px;
  color: #666;
}

.divider {
  border: none;
  border-top: 1px solid #ebedf0;
  margin: 16px 0;
}

.address-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.buttons {
  display: flex;
}

.buttons .van-button {
  margin-left: 10px;
}

.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: black;
  color: white;
  text-align: center;
}
</style>
